#!/bin/bash
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - interval
# END ENVIRONMENT VARIABLES

. $LKP_SRC/lib/env.sh
. $LKP_SRC/lib/http.sh
. $LKP_SRC/lib/wait.sh
setup_wait

# Collect CPU metrics
collect_cpu_metrics() {
  local cpu_line
  read -r cpu_line < /proc/stat
  local cpu_array=($cpu_line)
  local idle=${cpu_array[4]}
  local iowait=${cpu_array[5]}
  local system=${cpu_array[2]}
  local total=0

  for value in "${cpu_array[@]:1}"; do
    total=$((total + value))
  done

  cpu_idle=$(( (idle * 100) / total ))
  cpu_iowait=$(( (iowait * 100) / total ))
  cpu_system=$(( (system * 100) / total ))
}

# Collect disk usage metrics
collect_disk_metrics() {
  local disk_info
  disk_info=$(df -P | awk '
    NR==1 {next}
    {gsub(/%/, "", $5); if ($5 > max) {max=$5; mount=$6}}
    END {print max " " mount}'
  )
  disk_max_used=${disk_info%% *}
  disk_mount=${disk_info#* }
}

# Collect network metrics (simplified placeholder)
collect_network_metrics() {
  network_util=0
  network_errors=0
}

# Collect memory metrics
collect_memory_metrics() {
  while read -r key value _; do
    case $key in
      MemTotal:) totalmem=$((value >> 10)) ;;
      MemFree:) freemem=$((value >> 10)) ;;
    esac
  done < /proc/meminfo
}

# Collect uptime in minutes
collect_uptime() {
  read -r uptime _ < /proc/uptime
  uptime=$(( ${uptime%.*} / 60 ))
}

# Escape JSON strings
escape_json() {
  local str="$1"
  str=${str//\\/\\\\} # Escape backslashes
  str=${str//\"/\\\"} # Escape double quotes
  str=${str//\//\\\/} # Escape forward slashes
  str=${str//$'\t'/\\t} # Escape tabs
  str=${str//$'\n'/\\n} # Escape newlines
  str=${str//$'\r'/\\r} # Escape carriage returns
  escaped_json="$str"
}

# Static host information
hostname=$(hostname)
arch=$(uname -m)
nr_cpu=$(nproc)
nr_node=$(ls -d /sys/devices/system/node/node* | wc -l)
escape_json "$hostname"; escaped_hostname="$escaped_json"

# Main loop
while true; do
  # Collect metrics
  collect_cpu_metrics
  collect_disk_metrics
  collect_network_metrics
  collect_memory_metrics
  collect_uptime

  # Build JSON directly
  json_payload=$(printf '{
    "hostname": "%s",
    "arch": "%s",
    "nr_node": %d,
    "nr_cpu": %d,
    "freemem": %d,
    "freemem_percent": %d,
    "disk_max_used_string": "%s%% %s",
    "disk_max_used_percent": %d,
    "cpu_idle_percent": %d,
    "cpu_iowait_percent": %d,
    "cpu_system_percent": %d,
    "disk_io_util_percent": 0,
    "network_util_percent": %d,
    "network_errors_per_sec": %d,
    "uptime_minutes": %d,
  }' "$escaped_hostname" "$arch" "$nr_node" "$nr_cpu" \
    "$freemem" "$((freemem * 100 / totalmem))" \
    "$disk_max_used" "$disk_mount" "$disk_max_used" \
    "$cpu_idle" "$cpu_iowait" "$cpu_system" \
    "$network_util" "$network_errors" "$uptime")

  echo "$json_payload"
  exit
  # Upload metrics
  http_post "scheduler/host?report_metrics=true" "$json_payload"

  # Wait for the next interval
  wait_timeout ${interval:-10}
done
